package com.simplystupid.expensestracking;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class EditExpenses extends Activity {
	
	protected static final int PICK_DATE_DIALOG = 1;
	private EditText descText;
	private EditText amountText;
	private EditText dateText;
	private Calendar selectedDate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_expenses);
		
		descText = (EditText) findViewById(R.id.input_desc);
		amountText = (EditText) findViewById(R.id.input_amount);
		dateText = (EditText) findViewById(R.id.input_date);
		dateText.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(PICK_DATE_DIALOG);
				return false;
			}
		});
		
		Button saveBtn = (Button) findViewById(R.id.save_expenses);
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				values.put(MyExpensesProvider.DESCRIPTION, descText.getText().toString());
				values.put(MyExpensesProvider.AMOUNT, Double.valueOf(amountText.getText().toString()));
				values.put(MyExpensesProvider.EXPENSES_DATE, selectedDate.getTimeInMillis());
				getContentResolver().insert(MyExpensesAuthority.CONTENT_URI, values);
				
				finish();
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		Dialog dialog = new DatePickerDialog(this, 
				new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						selectedDate = Calendar.getInstance();
						selectedDate.set(year, monthOfYear, dayOfMonth);
						dateText.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
					}

				}, 
				c.get(Calendar.YEAR), 
				c.get(Calendar.MONTH), 
				c.get(Calendar.DAY_OF_MONTH));

		return dialog;
	}
	
}
